package com.lly.songhigh.activity;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lly.songhigh.R;
import com.lly.songhigh.adapter.LyricAdapter;
import com.lly.songhigh.adapter.MusicListAdapter;
import com.lly.songhigh.application.BaseApplication;
import com.lly.songhigh.constant.StringResouce;
import com.lly.songhigh.constant.URL;
import com.lly.songhigh.entity.LyricSentence;
import com.lly.songhigh.entity.MusicInfo;
import com.lly.songhigh.entity.SingerPIc;
import com.lly.songhigh.entity.dao.RecentPlay;
import com.lly.songhigh.eventbus.MyEvent;
import com.lly.songhigh.greendao.DaoSingleton;
import com.lly.songhigh.lrc.LyricDownloadManager;
import com.lly.songhigh.lrc.LyricLoadHelper;
import com.lly.songhigh.service.MediaPlayerService;
import com.lly.songhigh.utils.ChangeUtils;
import com.lly.songhigh.utils.SharedPreferencesUtils;
import com.lly.songhigh.view.MusicInfoPopupWindow;
import com.lly.songhigh.view.SlideDeleteListView;
import com.lly.songhigh.volley.StringRequestUtf;
import com.lly.songhigh.volley.VolleySingleton;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by 李新伟 on 15/10/30.
 * 歌曲播放界面
 */
public class PlayMusicActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, SeekBar.OnSeekBarChangeListener, SlideDeleteListView.RemoveListener {

    private VolleySingleton volleySingleton;
    private long singer_id, song_id; // 歌手Id, 歌曲Id
    private String artist; // 歌手名转码
    private String url;
    private Toolbar play_toolbar;
    private TextView play_total_time, play_start_time; // 歌曲总时间, 当前播放时间
    private SeekBar play_seekBar;
    // 上一首, 下一首, 分享, 背景图片, 循环状态
    private ImageView play_music_pre, play_music_next, play_music_share, play_music_singer_img, recycle_state;
    private CheckBox play_music_stop;
    private MediaPlayerService.MediaBinder mediaBinder;
    private Handler handler; // post一个Runnable
    private HandlerThread handlerThread; // 实现播放时间改变
    private Handler mHandler; // 发消息
    private ListView lrcLv;//歌词listView
    private TextView lrcEmptyTv;//没有歌词时显示
    private LyricAdapter mLyricAdapter;
    private LyricDownloadManager lyricDownloadManager;
    private LyricLoadHelper mLyricLoadHelper;//下载歌词helper类
    private int recycleState = 0; //标记循环状态, 0为全部循环, 1为随机播放, 2为单曲循环
    // 存放播放状态的图片数组
    private int[] imgs = {R.mipmap.play_icn_loop_prs, R.mipmap.play_icn_shuffle_prs, R.mipmap.play_icn_one_prs,};
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (service instanceof MediaPlayerService.MediaBinder) {
                mediaBinder = (MediaPlayerService.MediaBinder) service;
//                new ProgressThread().start();
                EventBus.getDefault().post(new MyEvent.OpenMusic(true));
                Log.i(TAG, "链接成功");
                lrcEmptyTv.setText("没有歌词, 点击手动下载");
                // 取得歌曲同目录下的歌词文件绝对路径
                String lyricFilePath = BaseApplication.lrcPath + "/" + mediaBinder.getSongName() + ".lrc";
                mLyricLoadHelper.loadLyric(lyricFilePath);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mediaBinder = null;
        }
    };
    private ImageView playMusicList;
    private View musicListView;
    private MusicListAdapter adapter;
    private List<MusicInfo> musicInfos;
    UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    private String shareUrl;
    private static final String TAG = "PlayMusicActivity";
    private DaoSingleton daoSingleton = DaoSingleton.getInstance();
    private TextView music_isPlaying;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.play_music);
        BaseApplication.getInstance().addActivity(this);
        EventBus.getDefault().register(this);
        initView();
        handler = new Handler();
        handlerThread = new HandlerThread("琪琪");
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper()) {
            // 接收消息
            public void handleMessage(Message msg) {
                // 执行时间改变的方法
                runBack();
                // 每500毫秒发送一条消息
                mHandler.sendEmptyMessageDelayed(1, 500);
            }
        };
        // 绑定服务
        Intent serviceIntent = new Intent(this, MediaPlayerService.class);
        bindService(serviceIntent, connection, BIND_AUTO_CREATE);

        initShare();
        QQShare();
    }

    private void runBack() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (mediaBinder != null) {
                    play_seekBar.setProgress(mediaBinder.getCurrentPosition());
                    mLyricLoadHelper.notifyTime(mediaBinder.getCurrentPosition());
                    play_start_time.setText(ChangeUtils.formatTime((long) mediaBinder.getCurrentPosition()));
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHandler.sendEmptyMessage(1);
        recycleState = SharedPreferencesUtils.getSharePreInt(this, "songHigh", "recycleState");
        recycle_state.setBackgroundResource(imgs[recycleState]);
        EventBus.getDefault().post(new MyEvent.RecycleMode(recycleState));
    }

    private void initView() {
        play_toolbar = (Toolbar) findViewById(R.id.play_toolbar);
        play_music_singer_img = (ImageView) findViewById(R.id.play_music_singer_img);
        play_total_time = (TextView) findViewById(R.id.play_total_time);
        play_music_next = (ImageView) findViewById(R.id.play_music_next);
        play_music_share = (ImageView) findViewById(R.id.play_music_share);
        play_music_pre = (ImageView) findViewById(R.id.play_music_pre);
        play_music_stop = (CheckBox) findViewById(R.id.play_music_stop);
        play_start_time = (TextView) findViewById(R.id.play_start_time);
        play_seekBar = (SeekBar) findViewById(R.id.play_seekBar);
        recycle_state = (ImageView) findViewById(R.id.recycle_state);
        playMusicList = (ImageView) findViewById(R.id.play_music_list);
        play_toolbar.setTitleTextColor(StringResouce.WHITE_COLOR);
        play_toolbar.setSubtitleTextColor(StringResouce.WHITE_COLOR);
        play_toolbar.setNavigationIcon(R.mipmap.toolbar_back);

        lrcLv = (ListView) findViewById(R.id.lv_lrc);
        lrcEmptyTv = (TextView) findViewById(R.id.lyric_empty);
        lrcEmptyTv.setOnClickListener(this);

        lyricDownloadManager = new LyricDownloadManager();
        //初始化helper类
        mLyricLoadHelper = new LyricLoadHelper();
        mLyricLoadHelper.setLyricListener(mLyricListener);
        //显示歌词的listview绑定适配器
        mLyricAdapter = new LyricAdapter(this);
        lrcLv.setAdapter(mLyricAdapter);
        lrcLv.setEmptyView(lrcEmptyTv);
        lrcLv.startAnimation(AnimationUtils.loadAnimation(PlayMusicActivity.this, android.R.anim.fade_in));
        play_toolbar.setNavigationOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        playMusicList.setOnClickListener(this);
        play_music_share.setOnClickListener(this);
        recycle_state.setOnClickListener(this);
        play_seekBar.setOnSeekBarChangeListener(this);
        play_music_stop.setChecked(false);
        play_music_stop.setOnCheckedChangeListener(this);
        play_music_pre.setOnClickListener(this);
        play_music_next.setOnClickListener(this);
    }

    private void initData() {
        volleySingleton = VolleySingleton.getInstance();
        singer_id = mediaBinder.getSingerId();
        song_id = mediaBinder.getSongId();
        try {
            artist = URLEncoder.encode(mediaBinder.getSingerName(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        loadPic();
    }

    /**
     * 加载歌手图片
     */
    private void loadPic() {
        url = URL.SINGER_ID + singer_id + URL.SONG_ID + song_id + URL.ARTIST_ID + artist + URL.SINGER_END;
        StringRequestUtf stringRequestUtf = new StringRequestUtf(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                SingerPIc singerPIc = gson.fromJson(response, SingerPIc.class);
                if (singerPIc.getData() != null && singerPIc.getData().size() > 0) {
                    String pic_url = singerPIc.getData().get(0).getPicUrls().get(0).getPicUrl();
                    Log.i(TAG, "图片网址 = " + pic_url);
                    Picasso.with(PlayMusicActivity.this).load(pic_url).into(play_music_singer_img);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(stringRequestUtf);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            mHandler.removeMessages(1);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int progress = seekBar.getProgress();
        mHandler.sendEmptyMessage(1);
        if (mediaBinder != null) {
            mediaBinder.seekTo(progress);
        }
    }

    /**
     * ListView滑动监听
     *
     * @param direction 滑动方向
     * @param position  滑动行布局的位置
     */
    @Override
    public void removeItem(SlideDeleteListView.RemoveDirection direction, int position) {
        // 判断如果删除的position和正在播放的position相同, 则播放下一首
        if (position == mediaBinder.getPosition()) {
            EventBus.getDefault().post(new MyEvent.PlayControl(6));
        }
        musicInfos.remove(position);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }

    private void insertToRecent() {
        MusicInfo musicInfo = mediaBinder.getMusicInfo();
        daoSingleton.getRecentPlayDao().insertOrReplace(new RecentPlay(musicInfo.getSongName(),
                musicInfo.getSingerName(), musicInfo.getAlbum(), musicInfo.getResouce(),
                musicInfo.getUrl(), (long) 0, musicInfo.getDuration(), musicInfo.getSongId()));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_music_next: // 下一曲
                EventBus.getDefault().post(new MyEvent.PlayControl(6));
                break;
            case R.id.play_music_pre: // 上一曲
                EventBus.getDefault().post(new MyEvent.PlayControl(7));
                break;
            case R.id.recycle_state:
                recycleState++;
                if (recycleState > 2) {
                    recycleState = 0;
                }
                EventBus.getDefault().post(new MyEvent.RecycleMode(recycleState));
                SharedPreferencesUtils.putSharePre(this, "songHigh", "recycleState", recycleState);
                recycle_state.setBackgroundResource(imgs[recycleState]);
                break;
            case R.id.play_music_list: // 弹出播放列表
                showPlayingList();
                break;
            case R.id.play_music_share:
                if (mediaBinder.getResouce().equals(StringResouce.RESOUCE_LOCAL)) {
                    Toast.makeText(PlayMusicActivity.this, StringResouce.LOCAL_NO_SHARE, Toast.LENGTH_SHORT).show();
                } else {
                    mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
                    //是否只有已登录用户才能打开分享选择页
                    mController.openShare(PlayMusicActivity.this, false);
                    QQShare();
                }
                break;
            case R.id.lyric_empty:
                showLrcDialog();
                break;
        }
    }

    private void showLrcDialog() {
        View view = View.inflate(this, R.layout.lrc_dialog, null);
        view.setMinimumWidth(250);
        final Dialog dialog = new Dialog(this, R.style.lrc_dialog);
        final Button okBtn = (Button) view.findViewById(R.id.ok_btn);
        final Button cancleBtn = (Button) view.findViewById(R.id.cancel_btn);
        final EditText artistEt = (EditText) view.findViewById(R.id.artist_tv);
        final EditText musicEt = (EditText) view.findViewById(R.id.music_tv);

        artistEt.setText(mediaBinder.getSongName());
        musicEt.setText(mediaBinder.getSingerName());
        View.OnClickListener btnListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v == okBtn) {
                    String artist = artistEt.getText().toString().trim(); // 歌手名
                    String music = musicEt.getText().toString().trim();// 歌名
                    if (TextUtils.isEmpty(artist) || TextUtils.isEmpty(music)) {
                        Toast.makeText(PlayMusicActivity.this, "歌手和歌曲不能为空",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        lrcEmptyTv.setText("稍等, 正在查询中...");
                        // 开始搜索
                        loadLyricByHand(music, artist);
                        dialog.dismiss();
                    }
                } else if (v == cancleBtn) {
                    dialog.dismiss();
                }
            }
        };
        okBtn.setOnClickListener(btnListener);
        cancleBtn.setOnClickListener(btnListener);
        dialog.setContentView(view);
        dialog.show();
    }
    private void initShare() {
        UMQQSsoHandler umqqSsoHandler = new UMQQSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        umqqSsoHandler.addToSocialSDK();
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qZoneSsoHandler.addToSocialSDK();
    }

    private void QQShare() {

        shareUrl = "http://m.dongting.com/?song_id=" + song_id + "&from=uc";
        QQShareContent qqShareContent = new QQShareContent();
        //设置分享文字
        qqShareContent.setShareContent(StringResouce.SHARE_CONTENT);
        //设置分享title
        qqShareContent.setTitle(StringResouce.SHARE_TITLE);
        //设置点击分享内容的跳转连接
        qqShareContent.setTargetUrl(shareUrl);

        mController.setShareMedia(qqShareContent);
        QZoneShareContent qzone = new QZoneShareContent();
        //设置分享文字
        qzone.setShareContent(StringResouce.SHARE_CONTENT);
        //设置分享内容的标题
        qzone.setTitle(StringResouce.SHARE_TITLE);
        //设置点击消息的跳转URL
        qzone.setTargetUrl(shareUrl);
        mController.setShareMedia(qzone);
    }

    /**
     * 弹出播放列表
     */
    private void showPlayingList() {
        musicListView = LayoutInflater.from(this).inflate(R.layout.music_list, null);
        SlideDeleteListView slideDeleteListView = (SlideDeleteListView) musicListView.findViewById(R.id.music_list);
        slideDeleteListView.setRemoveListener(this);
        music_isPlaying = (TextView) musicListView.findViewById(R.id.music_isPlaying);
        music_isPlaying.setText(mediaBinder.getSongName());
        slideDeleteListView.setSelector(R.color.transparent);
        musicInfos = mediaBinder.getMusicinfos();
        adapter = new MusicListAdapter(musicInfos);
        slideDeleteListView.setAdapter(adapter);
        MusicInfoPopupWindow popupWindow = new MusicInfoPopupWindow(this, onItemClickListener, musicListView);
        popupWindow.showAtLocation(playMusicList, Gravity.RIGHT, -50, 50);
    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            lrcEmptyTv.setText("没有歌词, 点击手动下载");
            // 点击发送消息播放当前位置的音乐
            EventBus.getDefault().post(new MyEvent.PlayMusicList(position));
            insertToRecent();
            music_isPlaying.setText(mediaBinder.getSongName());
        }
    };

    /**
     * 点击播放列表
     */
    public void onEvent(MyEvent.PlayMusicList playMusicList) {
        lrcEmptyTv.setText("没有歌词, 点击手动下载");
        setMusicInfo();
        // 取得歌曲同目录下的歌词文件绝对路径
        String lyricFilePath = BaseApplication.lrcPath + "/" + mediaBinder.getSongName() + ".lrc";
        mLyricLoadHelper.loadLyric(lyricFilePath);
    }

    /**
     * 上一曲和下一曲收消息
     */
    public void onEvent(MyEvent.PlayControl playControl) {
        setMusicInfo();
        insertToRecent();
        lrcEmptyTv.setText("没有歌词, 点击手动下载");
        // 取得歌曲同目录下的歌词文件绝对路径
        String lyricFilePath = BaseApplication.lrcPath + "/" + mediaBinder.getSongName() + ".lrc";
        mLyricLoadHelper.loadLyric(lyricFilePath);
        music_isPlaying.setText(mediaBinder.getSongName());
    }
    private void setMusicInfo() {
        play_seekBar.setMax(mediaBinder.getMax());
        play_total_time.setText(ChangeUtils.formatTime((long) mediaBinder.getMax()));
        play_toolbar.setTitle(mediaBinder.getSongName());
        play_toolbar.setSubtitle(mediaBinder.getSingerName());
        play_music_stop.setChecked(false);
        if (mediaBinder.getResouce().equals(StringResouce.RESOUCE_NET)) {
            initData();
        }
    }

    /**
     * 点击播放暂停多选按钮
     */
    public void onEvent(MyEvent.MediaPlay mediaPlay) {
        switch (mediaPlay.getWhat()) {
            case 2: // 暂停
                play_music_stop.setChecked(true);
                break;
            case 3: // 播放
                play_music_stop.setChecked(false);
                break;
        }
    }

    // 接收服务发来的消息, 刷新UI
    public void onEvent(MyEvent.RefreshUI refreshUI) {
        if (refreshUI.isPlaying()) {
            setMusicInfo();
            play_seekBar.setMax(mediaBinder.getMax());
        }
    }

    public void onEventMainThread(MyEvent.GetLrcCount count) {
        if (count.getCount() == 0) {
            lrcEmptyTv.setText("抱歉, 未能查询到指定歌词");
        }
    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (!isChecked) { // 暂停
            EventBus.getDefault().post(new MyEvent.MediaPlay(3));
        } else { // 播放
            EventBus.getDefault().post(new MyEvent.MediaPlay(2));
        }
    }

    private void loadLyricByHand(String songName, String singerName) {
        // 取得歌曲同目录下的歌词文件绝对路径
        String lyricFilePath = BaseApplication.lrcPath + "/" + songName + ".lrc";
        File lyricfile = new File(lyricFilePath);

        if (lyricfile.exists()) {
            // 本地有歌词，直接读取
            mLyricLoadHelper.loadLyric(lyricFilePath);
        } else {
            // 尝试网络获取歌词
            new LyricDownloadAsyncTask().execute(songName, singerName);
        }
    }
    //下载歌词异步任务
    class LyricDownloadAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            // 从网络获取歌词，然后保存到本地
            String lyricFilePath = lyricDownloadManager.searchLyricFromWeb(
                    params[1], params[0], mediaBinder.getSongName());
            // 返回本地歌词路径
            return lyricFilePath;
        }

        @Override
        protected void onPostExecute(String result) {
             Log.i(TAG, "网络获取歌词完毕，歌词保存路径:" + result);
            // 读取保存到本地的歌曲
            mLyricLoadHelper.loadLyric(result);
        }
    }

    //从loadHelper类调用下载歌词的方法,同时显示
    private LyricLoadHelper.LyricListener mLyricListener = new LyricLoadHelper.LyricListener() {
        @Override
        public void onLyricLoaded(List<LyricSentence> lyricSentences, int index) {
            if (lyricSentences != null) {
                mLyricAdapter.setLyric(lyricSentences);
                mLyricAdapter.setCurrentSentenceIndex(index);
                mLyricAdapter.notifyDataSetChanged();
                // 本方法执行时，lyricshow的控件还没有加载完成，所以延迟下再执行相关命令
            }
        }

        @Override
        public void onLyricSentenceChanged(int indexOfCurSentence) {
            mLyricAdapter.setCurrentSentenceIndex(indexOfCurSentence);
            mLyricAdapter.notifyDataSetChanged();
            lrcLv.smoothScrollToPositionFromTop(indexOfCurSentence,
                    lrcLv.getHeight() / 2, 500);
        }
    };

}
